""" FuzzyRule
    
    
    
    2006 (C) Pollini Andrea

    this file si released under LGPL license 2.0  or above.
"""

__author__ = "Pollini Andrea  nelson1977@gmail.com"

from FuzzyRuleExpression import FuzzyRuleExpression
from FuzzyOperators import IS,ISNOT, op_or
import FuzzyVariable 
import MembershipFunctions

class FuzzyRule(object):
    """
        Rule:	If (x1 is termX1) AND (x2 is termX2) ....  
        Then (y1 is termY1) AND (y2 is termY2) [weight: 1.0]
    """
    
    
    def __init__(self, name = "", weight = 1.0):
        self.name = name
        self.weight = weight
        self.antecedents = FuzzyRuleExpression()
        self.consequents = []
        
        
    def  addAntecedent(self, aFuzzyRule):
        
        self.antecedents.addTerm(aFuzzyRule)
        return self
        
    def addConsequent(self,aFuzzyVariable, aMembFuncName, aStatmentClass):
        self.consequents.append(aStatmentClass(aFuzzyVariable,aMembFuncName)) 
        
        
    def __str__(self):
        
        antecedent_str = self.antecedents.__str__()
        
        consequent_str = ""
        for cons_el in self.consequents:
            consequent_str += ", %s" % (cons_el)
            
        str_rep = "%s: \n\tIF %s THEN %s [weight = %f]\n\n" % (self.name,antecedent_str, consequent_str,self.weight)
        
        return str_rep
    
    
    
if __name__ == '__main__':
    frule = FuzzyRuleExpression()
    
    
    fv  = FuzzyVariable.FuzzyVariable("prova")
    fv.add(MembershipFunctions.make_membership_function("TRIANGULAR","basso",values=[0,1.2,2.5]))
    fv.add(MembershipFunctions.make_membership_function("TRIANGULAR","medio",values=[1,2.2,4.5]))
    fv.add(MembershipFunctions.make_membership_function("TRIANGULAR","alto",values=[2,4.2,5]))

    fv1  = FuzzyVariable.FuzzyVariable("prova1")
    fv1.add(MembershipFunctions.make_membership_function("TRIANGULAR","basso",values=[0,1.2,2.5]))
    fv1.add(MembershipFunctions.make_membership_function("TRIANGULAR","medio",values=[1,2.2,4.5]))
    fv1.add(MembershipFunctions.make_membership_function("TRIANGULAR","alto",values=[2,4.2,5]))
       
    fterm1 =  IS(fv,"basso")
    fterm2 =  ISNOT(fv1,"medio")
    fterm3 =  IS(fv1,"alto")
    frule.addTerm(fterm1)
    
    frule1 = FuzzyRuleExpression()    
    frule1.addTerm(fterm2)
    frule1.addTerm(fterm3)
    frule1.setConnectionOp(op_or)
    
    frule.addTerm(frule1)
    
    fr = FuzzyRule("rule1")
    fr.addAntecedent(fterm1)
    #fr.addAntecedent(fterm2)
    fr.addAntecedent(frule1)
    fr.addConsequent(fv1, "basso", IS)
    
    print fr